package com.huizhonglm.diap.ui.tab;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.EdgeEffectCompat;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.bruce.common.ActivityMgr;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.core.config.Constants;
import com.huizhonglm.diap.core.location.LocationService;
import com.huizhonglm.diap.core.location.LocationUtil;
import com.huizhonglm.diap.core.storage.model.LocationInfo;
import com.huizhonglm.diap.core.storage.pref.Keys;
import com.huizhonglm.diap.core.storage.pref.Preferences;
import com.huizhonglm.diap.core.utils.LogUtil;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.user.LoginActivity;
import com.huizhonglm.diap.widget.TabhostViewPager;

import java.lang.reflect.Field;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-01 23:25
 */
public class TabhostActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener,
        ViewPager.OnPageChangeListener {

    private TabhostViewPager mViewPager;
    private RadioButton homeRbtn;
    private RadioButton nearRbtn;
    private RadioButton marketRbtn;
    private RadioButton meRbtn;

    TabhostHomeFragment homeFragment;
    TabhostNearFragment nearFragment;
    TabhostMarketFragment marketFragment;
    TabhostMeFragment meFragment;

    private boolean isExit = false;

    private EdgeEffectCompat leftEdge;// ViewPager左边缘对象
    private EdgeEffectCompat rightEdge;// ViewPager右边缘对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabhost);
        assignViews();
        initEdgeEffectCompat();
        registerLocationReceiver();
        LocationInfo locInfo = LocationUtil.getLocation();
        if (locInfo == null || locInfo.getTime() > 5000L) {
            startService(new Intent(this, LocationService.class));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean needToLogin = Preferences.getInstance().getBoolean(Keys.needToLogin, false);
        if (needToLogin) {
            Preferences.getInstance().edit().putBoolean(Keys.needToLogin, false).apply();
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        homeRbtn.setChecked(true);
    }

    @Override
    protected void assignViews() {
        homeFragment = new TabhostHomeFragment();
        nearFragment = new TabhostNearFragment();
        marketFragment=new TabhostMarketFragment();
        meFragment = new TabhostMeFragment();

        mViewPager = (TabhostViewPager) findViewById(R.id.tabhost_vp);
        RadioGroup rgp = (RadioGroup) findViewById(R.id.tabhost_rg);
        homeRbtn = (RadioButton) findViewById(R.id.tabhost_home_rbtn);
        nearRbtn = (RadioButton) findViewById(R.id.tabhost_near_rbtn);
        marketRbtn = (RadioButton) findViewById(R.id.tabhost_market_rbtn);
        meRbtn = (RadioButton) findViewById(R.id.tabhost_me_rbtn);

        mViewPager.setScrollable(false);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setAdapter(new TabAdapter(getSupportFragmentManager()));
        mViewPager.setOnPageChangeListener(this);
        rgp.setOnCheckedChangeListener(this);
        homeRbtn.setChecked(true);
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.tabhost_home_rbtn:
                mViewPager.setCurrentItem(0, false);
                break;
            case R.id.tabhost_near_rbtn:
                mViewPager.setCurrentItem(1, false);
                break;
            case R.id.tabhost_market_rbtn:
                mViewPager.setCurrentItem(2, false);
                break;
            case R.id.tabhost_me_rbtn:
                mViewPager.setCurrentItem(3, false);
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float v, int i1) {
        if(leftEdge != null && rightEdge != null){
            leftEdge.finish();
            rightEdge.finish();
            leftEdge.setSize(0, 0);
            rightEdge.setSize(0, 0);
        }
    }

    @Override
    public void onPageSelected(int position) {
        switch (position){
            case 0:
                homeRbtn.setChecked(true);
                break;
            case 1:
                nearRbtn.setChecked(true);
                break;
            case 2:
                marketRbtn.setChecked(true);
                break;
            case 3:
                meRbtn.setChecked(true);
                break;
            default:
                homeRbtn.setChecked(true);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int position) {
    }

    /**
     * 反射ViewPager左右边缘对象（用来去除滑动到边缘时的渐变色）
     */
    private void initEdgeEffectCompat(){
        try {
            Field leftEdgeField = mViewPager.getClass().getDeclaredField("mLeftEdge");
            Field rightEdgeField = mViewPager.getClass().getDeclaredField("mRightEdge");
            if(leftEdgeField != null && rightEdgeField != null){
                leftEdgeField.setAccessible(true);
                rightEdgeField.setAccessible(true);
                leftEdge = (EdgeEffectCompat) leftEdgeField.get(mViewPager);
                rightEdge = (EdgeEffectCompat) rightEdgeField.get(mViewPager);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void registerLocationReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.LOCATE_SERVICE_COMPLATE_ACTION);
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(locationReceiver, filter);
    }

    private void exitByTwoClick() {
        Timer tExit;
        if (!isExit) {
            isExit = true; // 准备退出
            ToastUtil.makeTextShort("再按一次退出程序");
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            ActivityMgr.getInstance().exitApp();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exitByTwoClick();
                return true;
            default:
                return super.onKeyDown(keyCode, event);
        }
    }

    private BroadcastReceiver locationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.LOCATE_SERVICE_COMPLATE_ACTION)) {
                LocationInfo locInfo = (LocationInfo) intent.getSerializableExtra(Constants.LOCATE_SERVICE_LOCATION);
                if (locInfo != null) {
                    LogUtil.print("locationService - tabhost >>> receiver - lng=" + locInfo.getLongitude() + "-lat=" + locInfo.getLatitude());
                    if (homeFragment != null) {
                        homeFragment.setLocationCity(locInfo);
                    }
                    if (nearFragment != null) {
                        nearFragment.setLocationPoint(locInfo);
                    }
                } else {
                    LogUtil.print("locationService - tabhost >>> receiver - failured");
                }
            }
        }
    };

    public class TabAdapter extends FragmentStatePagerAdapter {

        public TabAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            switch (i) {
                case 0:
                    return homeFragment;
                case 1:
                    return nearFragment;
                case 2:
                    return marketFragment;
                case 3:
                    return meFragment;
                default:
                    return homeFragment;
            }
        }

        @Override
        public int getCount() {
            return 4;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(this, LocationService.class));
        unregisterReceiver(locationReceiver);
    }
}
